Today, you will load a filtered gapminder dataset - with a subset of data on global development from 1952 - 2007 in increments of 5 years - to capture the period between the Second World War and the Global Financial Crisis.
Your task: Explore the data and visualise it in both static and animated ways, providing answers and solutions to 7 questions/tasks below.
First, start with installing the relevant packages ‘tidyverse’, ‘gganimate’, and ‘gapminder’.
## Warning: package 'tidyverse' was built under R version 4.0.2
## -- Attaching packages ----------------------------------------- tidyverse 1.3.0 --
## v ggplot2 3.3.1 v purrr 0.3.4
## v tibble 3.0.1 v dplyr 1.0.0
## v tidyr 1.1.0 v stringr 1.4.0
## v readr 1.3.1 v forcats 0.5.0
## -- Conflicts -------------------------------------------- tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag() masks stats::lag()
## Warning: package 'gganimate' was built under R version 4.0.2
## Warning: package 'gapminder' was built under R version 4.0.2
## Warning: package 'gifski' was built under R version 4.0.2
First, see which specific years are actually represented in the dataset and what variables are being recorded for each country. Note that when you run the cell below, Rmarkdown will give you two results - one for each line - that you can flip between.
unique(gapminder$year)
## [1] 1952 1957 1962 1967 1972 1977 1982 1987 1992 1997 2002 2007
head(gapminder)
## # A tibble: 6 x 6
## country continent year lifeExp pop gdpPercap
## <fct> <fct> <int> <dbl> <int> <dbl>
## 1 Afghanistan Asia 1952 28.8 8425333 779.
## 2 Afghanistan Asia 1957 30.3 9240934 821.
## 3 Afghanistan Asia 1962 32.0 10267083 853.
## 4 Afghanistan Asia 1967 34.0 11537966 836.
## 5 Afghanistan Asia 1972 36.1 13079460 740.
## 6 Afghanistan Asia 1977 38.4 14880372 786.
The dataset contains information on each country in the sampled year, its continent, life expectancy, population, and GDP per capita.
Let’s plot all the countries in 1952.
theme_set(theme_bw()) # set theme to white background for better visibility
ggplot(subset(gapminder, year == 1952), aes(gdpPercap, lifeExp, size = pop)) +
geom_point() +
scale_x_log10()
We see an interesting spread with an outlier to the right. Answer the following questions, please:
Q1. Why does it make sense to have a log10 scale on x axis? The log10 scale on the x axis visually pool together the datapoints. This is nice since there is one country that sticks out from the rest in relation to gdp per capita. This is evident when plotting the data on a regular scale i.e., commenting out the scale_x_log10(). So, to make it more visually intuitive, log scale makes sure that the datapoint are spread out more evenly across the graph. This is achieved as the log scale ensure that the numerical data over a very wide range of values is displayed in a compact way.
Q2. What country is the richest in 1952 (far right on x axis)?
gapminder %>%
filter(year == 1952) %>% # Finds rows for all countries at the year 1952
select(country, gdpPercap) %>% # Selects the columns country and gdpPercap
arrange(desc(gdpPercap)) # Arrange the gdpPercep data in descending order
## # A tibble: 142 x 2
## country gdpPercap
## <fct> <dbl>
## 1 Kuwait 108382.
## 2 Switzerland 14734.
## 3 United States 13990.
## 4 Canada 11367.
## 5 New Zealand 10557.
## 6 Norway 10095.
## 7 Australia 10040.
## 8 United Kingdom 9980.
## 9 Bahrain 9867.
## 10 Denmark 9692.
## # ... with 132 more rows
So as can be seen, Kuwait was by far the richest country in 1952 with a factor of 10 from the next richest country.
You can generate a similar plot for 2007 and compare the differences
ggplot(subset(gapminder, year == 2007), aes(gdpPercap, lifeExp, size = pop)) +
geom_point() +
scale_x_log10()
The black bubbles are a bit hard to read, the comparison would be easier with a bit more visual differentiation.
Q3. Can you differentiate the continents by color and fix the axis labels?
# Subsetting the data to only keep the rows for the year 2007
gapminder2007 <- gapminder %>%
filter(year == "2007")
# ggplot showing coloring by continent
gapminder2007 %>%
ggplot(aes(x = gdpPercap, y = lifeExp, size = pop, color = continent)) +
# Making the points more see-through
geom_point(alpha=0.7) +
scale_x_log10() +
# Changing the scale for the size of the data points and changing the name from "pop" to "Population".
scale_size(range = c(1, 10), name="Population") +
# Specifying the title, x label and y label.
labs(title = "Continents in 2007",
x = "GDP per capita",
y = "Life Expectancy")
Q4. What are the five richest countries in the world in 2007?
gapminder %>%
# Finds rows for all countries at the year 2007
filter(year == 2007) %>%
# Selects the columns country and gdpPercap
select(country, gdpPercap) %>%
# Arrange the gdpPercep data in descending order
arrange(desc(gdpPercap)) %>%
# Choosing only the first 5
head(, n=5)
## # A tibble: 5 x 2
## country gdpPercap
## <fct> <dbl>
## 1 Norway 49357.
## 2 Kuwait 47307.
## 3 Singapore 47143.
## 4 United States 42952.
## 5 Ireland 40676.
In descending order, the richest countries in 2007 was Norway, Kuwait, Singapore, The United States and Ireland.
The comparison would be easier if we had the two graphs together, animated. We have a lovely tool in R to do this: the gganimate package. And there are two ways of animating the gapminder ggplot.
The first step is to create the object-to-be-animated
anim <- ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop)) +
geom_point() +
scale_x_log10() # convert x to log scale
anim
This plot collates all the points across time. The next step is to split it into years and animate it. This may take some time, depending on the processing power of your computer (and other things you are asking it to do). Beware that the animation might appear in the ‘Viewer’ pane, not in this rmd preview. You need to knit the document to get the viz inside an html file.
anim + transition_states(year,
transition_length = 1,
state_length = 1)
Notice how the animation moves jerkily, ‘jumping’ from one year to the next 12 times in total. This is a bit clunky, which is why it’s good we have another option.
This option smoothes the transition between different ‘frames’, because it interpolates and adds transitional years where there are gaps in the timeseries data.
anim2 <- ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop)) +
geom_point() +
scale_x_log10() + # convert x to log scale
transition_time(year)
anim2
The much smoother movement in Option 2 will be much more noticeable if you add a title to the chart, that will page through the years corresponding to each frame.
Q5 Can you add a title to one or both of the animations above that will change in sync with the animation? [hint: search labeling for transition_states() and transition_time() functions respectively]
# For the transition_state()
anim + transition_states(year,
transition_length = 1,
state_length = 1) +
# Using the labs function and the "closest_state" function that works with transition_states()
labs(title = "{closest_state}")
# For the transition_time()
anim2 <- ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop)) +
geom_point() +
scale_x_log10() + # convert x to log scale
transition_time(year)+
# Using the labs function and the "frame_time" function that works with transition_time()
labs(title = "Year: {frame_time}")
anim2
Q6 Can you made the axes’ labels and units more readable? Consider expanding the abreviated lables as well as the scientific notation in the legend and x axis to whole numbers.[hint:search disabling scientific notation]
# This time I will only do it for the anim2
# Found on StackOverflow, the scipen option should disable the scientific notation when set to a high value as this value determines how likely it is that the scientific notation will be triggered.
options(scipen=999)
anim2 <- ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop)) +
geom_point() +
scale_x_log10() +
transition_time(year)+
labs(title = "Year: {frame_time}",
# Specifying labels for x and y
x = "GDP per capita",
y = "Life Expectancy")
anim2
Q7 Come up with a question you want to answer using the gapminder data and write it down. Then, create a data visualisation that answers the question and explain how your visualization answers the question.
# The question, I want to answer is how the life expectancy differs across continents and how they have changed from 1952 to 2007. I visualize this by making a side-by-side bar plot that shows the mean life expectancy per continent for 1952 and 2007, respectively.
gapminder %>%
# First, I subset the data to only contain rows for the years 1952 and 2007
filter(year == "1952"|year == "2007") %>%
# Then, I group the subsetted data by continent and then by year
group_by(continent, year) %>%
# I then summarise the data to show the mean life expectancy for each group
summarise(avg_lifeExp = mean(lifeExp)) %>%
# Lastly, I plot the data
ggplot() +
# To make it more visually intuitive, I reorder the data in descending order. This is done using the reorder function. Furthermore, I color each continent in distinct colors. And as I have already calculated the mean, I just want to show the data points as they are so I choose the stat = "identity".
geom_bar(aes(reorder(continent, avg_lifeExp), avg_lifeExp,
fill = continent), stat = "identity") +
# To make the side-by-side graph, I specify the facet wrap to be by year
facet_wrap(~year)+
# Adding labels to make it more visually appealing
labs(title = "Life Expectancy in 1952 and 2007", x = "Continents", y = "Life Expectancy")+
# The coord flip is to ensure that the continent names are easy to read as this flips the x and y axis so the bars are horizontal instead of vertical
coord_flip()
## `summarise()` regrouping output by 'continent' (override with `.groups` argument)
As can be seen from the plot, the order of highest to lowest mean life expectancies across continents doesn’t change. However, in general life expectancy changes for all continents from 1952 to 2007. E.g., Oceania had the highest life expectancy in 1952 with an average life expectancy of approx. 70. In 2007, Oceania is still the continent with the highest life expectancy albeit this time it is over 80 years.